package com.qf.xiaomi.web.filter;

import com.qf.xiaomi.pojo.User;
import com.qf.xiaomi.service.UserService;
import com.qf.xiaomi.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLDecoder;

/**
 *
 * 自动登录 过滤器
 *  1. 先判断是否登录了， 如果登录了，直接放行
 *  2. 如果未登录，实现自动登录
 *      2.1 从cookie中获取账号和密码信息
 *      2.2 校验账户和密码是否正确
 *      2.3 如果正确，保存登录状态到session中， 再放行
 *      2.4 如果错误，直接放行
 * @author 千锋教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
@WebFilter("/*")
public class AutoLoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //转换为 子类对象
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        String requestURI = req.getRequestURI();
        if("/login.jsp".equalsIgnoreCase(requestURI) || "/userServlet".equalsIgnoreCase(requestURI) || "/register.jsp".equalsIgnoreCase(requestURI))
        {
            filterChain.doFilter(req, resp);
            return;
        }

        //获取登录状态
        HttpSession session = req.getSession();
        Object user = session.getAttribute("user");
        //如果用户不为空，（说明已登录）则放行
        if(user != null){
            //放行
            filterChain.doFilter(req, resp);
            return;
        }

        //实现自动登录过程
        //从cookie中获取账户信息
        Cookie[] cookies = req.getCookies();
        if(cookies !=null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();

                if("user".equalsIgnoreCase(name)) {
                    String value = cookie.getValue();
                    //解码
                    String decode = URLDecoder.decode(value, "utf-8");
                    //切割
                    String[] split = decode.split("#");
                    String username = split[0];
                    String password = split[1];
                    //执行登录操作
                    UserService service = new UserServiceImpl();
                    User userDb = service.findByUserAndPwd(username, password);
                    if(userDb != null) {
                        //如果为不为空，则登录成功
                        session.setAttribute("user", userDb);
                    }
                    filterChain.doFilter(req, resp);
                    return;
                }
            }
        }

        resp.sendRedirect("/login.jsp");

    }

    @Override
    public void destroy() {

    }
}
